package com.gsit.job.services;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;

import org.springframework.stereotype.Component;

import com.gsit.job.domain.Person;

@Component
public class UrlParser {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		UrlParser parser = new UrlParser();
		List<String> urls = new ArrayList<String>();
		urls.add("../resumedatabase/resume.html?resid=48131097;uid=50139300;words=;tokens=;emps=;r=;ucid=1;ufd=1;mosf=0;cn=0;sig=rs-1-bcf3e2d34848027d7e8fb578714db66d-1;la=en;");
		urls.add("http://recruiter.monsterindia.com/v2/resumedatabase/resume.html?resid=28281748&uid=23362856&&type=private&folderID=13789689&section=3&source=0&mosf=0&cn=0");
		
		List<Person> persons = parser.parse( urls);
		//parser.parse("http://recruiter.monsterindia.com/v2/resumedatabase/resume.html?resid=28281748&uid=23362856&&type=private&folderID=13789689&section=3&source=0&mosf=0&cn=0");

		PersonFileWriter fileWriter = new PersonFileWriter();
		for (Person person : persons) {
			System.out.println(person.getResid());
			//fileWriter.write(person, "this is first ");
		}
		
		
	}
	
	public List<Person>  parse(List<String> urls){
		List<Person> persons = new ArrayList<Person>(); 
		
		for (String url : urls) {
			persons.add(parse(url));
		}
		//System.out.println(">>>>>.... total size is "+persons.size());
		
		return persons;
	}
	
	private Person parse(String url){
		Person person = new Person();
		parseData(trimBaseUrl(url), person);
		person.setUrl(url);
		person.setCreatedDate(new Date());
		person.setIsResumeCaptured(false);
		//System.out.println(person);
		
		return person;
		
	}
	
	private String trimBaseUrl(String url){
		StringTokenizer stringTokenizer = new StringTokenizer(url,"?");
		String finalUrl = "";
		while (stringTokenizer.hasMoreTokens()) {
			finalUrl = stringTokenizer.nextToken();
	     }
		
		
		
		return finalUrl;
	}
	
	private void parseData(String url,Person person  ){
		String str = url.contains("&") ? "&":";";
		StringTokenizer stringTokenizer = new StringTokenizer(url,str);
		while (stringTokenizer.hasMoreTokens()) {
			String finalUrl = stringTokenizer.nextToken();
			if(finalUrl!=""){
				String fieldName =  finalUrl.substring(0, finalUrl.indexOf("="));
				String value =  finalUrl.substring( finalUrl.indexOf("=")+1);
				if(fieldName.trim().equalsIgnoreCase("resid")){
					person.setResid(value);
				}else if(fieldName.trim().equalsIgnoreCase("uid")){
					person.setUid(value);
				}
				
				
			}
			
	     }
	}
	
	

}
